﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using NPOI.HSSF.UserModel;
using OfficeOpenXml;
using System.Web.UI.WebControls;
using System.Web.UI;


namespace GPS.Controllers.GPS_Export
{
    public class GPS_DT_TN_PhanCongController : Controller
    {
        //
        // GET: /ExportHocVien_HopDong/
        #region Index
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        public GPS.MODELS.ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();
            string userId = User.Identity.GetUserId();
            ApplicationUser _currentUser = dbUser.Users.Find(userId);
            return _currentUser;
        }
        public void initialCategorySearchAction(View_Export_DT_DTTN_PHANCONG viewModel)
        {
            string DVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            ViewBag.checkuser = DVGTVT_MA;
            string getdvgtvt_Ma = GPS.DAL.Check_User.CheckUser(this.getCurrentUser().MA_TINHTP, viewModel.pDVGTVT_MA);
            viewModel.pDVGTVT_MA = getdvgtvt_Ma;
        }
        public ActionResult Index(View_Export_DT_DTTN_PHANCONG SearchModel, int? currentPage)
        {
            initialCategorySearchAction(SearchModel);
            if (SearchModel.SearchButton == "Xuất hợp đồng")
            {
                DataSet ds = GetdataQuyetDinhToChucKyThi(SearchModel.pDVGTVT_MA, SearchModel.pQD_ID);
                Export_DT_DTTN_PHANCONG _model = new Export_DT_DTTN_PHANCONG();
                List<Export_DT_DTTN_PHANCONG> lstModel = new List<Export_DT_DTTN_PHANCONG>();
                if (ds != null)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        _model.DVGTVT_TEN = ds.Tables[0].Rows[i]["DVGTVT_TEN"] == null ? "" : ds.Tables[0].Rows[i]["DVGTVT_TEN"].ToString();
                        _model.DDTTN_QD_SO_QD = ds.Tables[0].Rows[i]["DDTTN_QD_SO_QD"] == null ? "" : ds.Tables[0].Rows[i]["DDTTN_QD_SO_QD"].ToString();
                        if (ds.Tables[0].Rows[i]["DDTTN_QD_NGAY_QD"] != null)
                        {
                            _model.DDTTN_QD_NGAY_QD = Convert.ToDateTime(ds.Tables[0].Rows[i]["DDTTN_QD_NGAY_QD"].ToString());
                        }
                        _model.DS_KH_TEN = ds.Tables[0].Rows[i]["DS_KH_TEN"] == null ? "" : ds.Tables[0].Rows[i]["DS_KH_TEN"].ToString();
                    }
                    _model.LIST_pRetDieu1 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[1]);
                    _model.LIST_pRetDieu2 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[2]);
                    _model.LIST_pRetDieu3 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[3]);
                    //_model.LIST_pRetDSDTTN = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[4]);
                }
                byte[] contentFile = null;
                contentFile = GPS.ENTITYS.EXPORTWORD_DT_DTTN_PHANCONG.EXPORTWORD_DT_DTTNPC(Server.MapPath("~/Templates/GPS_Word/QuyetDinhToChucKyThi.docx"), _model, "DocxGenericReport");
                string nameOutput = string.Format("QuyetDinhToChucKyThi_{0}_{1}.docx", SearchModel.pKH_MA, DateTime.Now.ToShortDateString().Replace("/", "_"));
                return File(contentFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", nameOutput);
            }
            else
            {
                return View(SearchModel);
            }
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0) try
                {
                    string path = Path.Combine(Server.MapPath("~/Files"),
                    Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    return Json(new
                    {
                        Error = false,
                        Message = "File Uploaded Successfully..!!!",
                        FilePath = file.FileName
                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new
                    {
                        Error = false,
                        Message = "File Not Uploaded"
                    }, JsonRequestBehavior.AllowGet);
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return View();
        }

        public DataSet GetdataQuyetDinhToChucKyThi(string madvgtvt, string QD_ID)
        {
            DataSet ds = OracleHelper.ExecuteDataset(_db.DbContext.Database.Connection.ConnectionString, CommandType.StoredProcedure, "GPS_DAOTAO.GPS_DAOTAO_DTTN_PHANCONG"
                                                                   , new OracleParameter("pDVGTVT_MA", OracleDbType.Varchar2, string.IsNullOrWhiteSpace(madvgtvt) ? DBNull.Value : (object)madvgtvt, ParameterDirection.Input)
                                                                   , new OracleParameter("pDTTN_QD_ID", OracleDbType.Int64, string.IsNullOrWhiteSpace(QD_ID) ? DBNull.Value : (object)QD_ID, ParameterDirection.Input)
                                                                   , new OracleParameter("pRetHeader", OracleDbType.RefCursor, ParameterDirection.Output)
                                                                   , new OracleParameter("pRetDieu1", OracleDbType.RefCursor, ParameterDirection.Output)
                                                                   , new OracleParameter("pRetDieu2", OracleDbType.RefCursor, ParameterDirection.Output)
                                                                    , new OracleParameter("pRetDieu3", OracleDbType.RefCursor, ParameterDirection.Output)
                                                                   , new OracleParameter("pRetDSDTTN", OracleDbType.RefCursor, ParameterDirection.Output)
                                                                  );
            return ds;
        }

        public JsonResult AutoCompleteKH_MA(string term, string dvgtvt_ma)
        {
            string _ma_DVGT = dvgtvt_ma.Split(':')[0];
            var rs = _db.Filter<DDTTN_QD>(x => x.DDTTN_QD_TENKHOA.ToUpper().Contains(term.ToUpper()) || x.DDTTN_QD_SO_QD.ToUpper().Contains(term.ToUpper()) && x.DDTTN_QD_DVGTVT_MA == _ma_DVGT);
            return Json(rs, JsonRequestBehavior.AllowGet);
        }


        #endregion


        //public FileResult ShowDocument(string FilePath, string madvgtvt, string makhoahoc, string maquyetdinh)
        //{
        //    DataSet ds = new DataSet();
        //    ds = RunPKG(madvgtvt, maquyetdinh);
        //    Export_DT_DTTN_PHANCONG _model = new Export_DT_DTTN_PHANCONG();
        //    List<Export_DT_DTTN_PHANCONG> lstModel = new List<Export_DT_DTTN_PHANCONG>();
        //    if (ds != null)
        //    {
        //        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //        {
        //            _model.DVGTVT_TEN = ds.Tables[0].Rows[i]["DVGTVT_TEN"] == null ? "" : ds.Tables[0].Rows[i]["DVGTVT_TEN"].ToString();
        //            _model.DDTTN_QD_SO_QD = ds.Tables[0].Rows[i]["DDTTN_QD_SO_QD"] == null ? "" : ds.Tables[0].Rows[i]["DDTTN_QD_SO_QD"].ToString();
        //            if (ds.Tables[0].Rows[i]["DDTTN_QD_NGAY_QD"] != null)
        //            {
        //                _model.DDTTN_QD_NGAY_QD = Convert.ToDateTime(ds.Tables[0].Rows[i]["DDTTN_QD_NGAY_QD"].ToString());
        //            }
        //            _model.DS_KH_TEN = ds.Tables[0].Rows[i]["DS_KH_TEN"] == null ? "" : ds.Tables[0].Rows[i]["DS_KH_TEN"].ToString();
        //        }
        //        _model.LIST_pRetDieu1 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[1]);
        //        _model.LIST_pRetDieu2 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[2]);
        //        _model.LIST_pRetDieu3 = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[3]);
        //        _model.LIST_pRetDSDTTN = COMMON.Helpers.MapDataTableToList<Export_DT_DTTN_PHANCONG>(ds.Tables[4]);
        //    }

        //    // _model.KHOAHOC_TEN = item.HV_KH_MA;
        //    byte[] contentFile = null;
        //    contentFile = GPS.ENTITYS.EXPORTWORD_DT_DTTN_PHANCONG.EXPORTWORD_DT_DTTNPC(Server.MapPath("~/Templates/GPS_Word/BienBanHopPhanCongChamThi.docx"), _model, "DocxGenericReport");
        //    string nameOutput = "BienBanHopPhanCongChamThi_" + _model.HOTEN + DateTime.Now.ToShortDateString() + ".docx";
        //    return File(contentFile, GetMimeType(contentFile));
        //}
        //private string GetMimeType(string fileName)
        //{
        //    string mimeType = "application/unknown";
        //    string ext = System.IO.Path.GetExtension(fileName).ToLower();
        //    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        //    if (regKey != null && regKey.GetValue("Content Type") != null)
        //        mimeType = regKey.GetValue("Content Type").ToString();
        //    return mimeType;
        //}

    }
}